#################################################################################

source('lisa_perm.R')
source('pm.R')

#---------------------------Municipal Value Added, 2011----------------------------#
va<-read.table('data/va_2011.csv',header=TRUE,sep=';')
va<-subset(va, !(va$Divipola %in% c(5475,5873)))

#################################################################################
#-----------------------------Antioquia's Shape---------------------------------#

library(spdep)
library(maptools)

# Load Antioquia's shape file
ant<-readShapePoly('data/antioquia.shp')


# Set rownames, namely, change feature identifier in spatial object
row.names(ant)<-as.character(ant$ID_ESPAC_2)

# Check rownames, to confirm that the preceeding had the desired effect
identical(row.names(ant),sapply(ant@polygons, function(x) slot(x,"ID")))

# Re-order
ant<-ant[order(row.names(ant)),]

# Indeed, the reordering worked
row.names(ant)
ant<-subset(ant, !(ant$ID_ESPAC_2 %in% c(5475,5873)))

#################################################################################
#-----------------------------Travel Times Matrix-------------------------------#

odh<-read.table('data/od-matrix-h.csv',sep=';')

identical(va$Divipola,as.numeric(ant$ID_ESPAC_2),as.numeric(rownames(odh)))

#################################################################################
#------------------------------Market Potential---------------------------------#

#W<-as.matrix(odh);colnames(W)<-rownames(W)

#va$pm<-pm(va,W,mass.var='VA')$pmR

#################################################################################

library(shiny)

# Define server logic for random distribution application
shinyServer(function(input, output, session) {
    
    output$plot1 <- renderPlot({
        
        W<-as.matrix(odh);colnames(W)<-rownames(W)
        # The matrix is rescaled. Now a travel time of half an hour equals
        # one (1). A travel time of an hour equals one and a half (1.5).
        if(input$self==TRUE){W<-W+.5;W[W<=1]<-1}
        va$pm<-pm(va,W,mass.var='VA')$pmR
        
        W<-as.matrix(odh);colnames(W)<-rownames(W)
        W<-(W>=0 & W<input$hdist)
        W<-W/rowSums(W)
        lw<-mat2listw(W,row.names=rownames(W),style='W')
        
        lmoran<-lisa.perm(va[,'pm'],lw,perm=input$perm)
        plot.lisaPerm(lmoran,ant,signif=input$signif,legend.title=paste('Consumo de energ?a',input$year,sep=', '))
    })
    
    output$plot2 <- renderPlot({
        
        W<-as.matrix(odh);colnames(W)<-rownames(W)
        W<-(W>=0 & W<input$hdist)
        W<-W/rowSums(W)
        lw<-mat2listw(W,row.names=rownames(W),style='W')
        
        lmoran<-lisa.perm(va[,'VA'],lw,perm=input$perm)
        plot.lisaPerm(lmoran,ant,signif=input$signif,legend.title=paste('Consumo de energ?a',input$year,sep=', '))
    })
})




